package com.starmark.gateway.springcloud.provider.utils;

import cn.hutool.core.util.StrUtil;
import com.starmark.gateway.springcloud.provider.constants.GatewayConstant;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.AntPathMatcher;

import org.springframework.web.server.ServerWebExchange;

/**
 * @author starmark
 * @date 20-2-14  下午5:10
 */
public final class RequestHelper {


    /**
     * 获取请求的中工程ID
     * @param request 请求
     * @return 工程ID
     */
    public static String getRequestProjectCode(ServerHttpRequest request) {
        String projectCode = request.getHeaders().getFirst(GatewayConstant.X_CLIENT_PROJECT_CODE);
        if (StrUtil.isEmpty(projectCode)) {
            projectCode = request.getQueryParams().getFirst(GatewayConstant.X_CLIENT_PROJECT_CODE);
        }
        //从URL获取工程ID
        if(StrUtil.isEmpty(projectCode)){
          String path=  request.getURI().getPath();
            path=path.replaceFirst("/","");
          if(path.contains("/")) {
              projectCode = path.substring(0, path.indexOf("/")  );
          }
        }
        return projectCode;
    }

    /**
     * 获取用户信息
     * @param exchange
     * @return 用户ID
     */
    public static String getUserId(ServerWebExchange exchange) {

        return exchange.getAttributes().getOrDefault(GatewayConstant.X_CLIENT_TOKEN_USER_ID,"")+"";
    }

    /**
     * @param url         请求URL
     * @param projectCode 工程编码
     * @return 处理后的Url
     */
    public static  String handleUrl(String url, String projectCode) {
        String newUrl = url;
        if (url.startsWith("/" + projectCode)) {
            newUrl = newUrl.replaceFirst("/" + projectCode, "");
        }

        return newUrl;
    }


    /**
     * @param url 请求URL
     * @return 处理后的Url
     */
    public static  String handleEndUrl(String url) {
        String result=url;
        if (!url.startsWith("/")) {
            result=  "/"+result;
        }
        if (!url.endsWith("**")) {
            result=  result+ "**";
        }
        return result;
    }

    /**
     * 判断是否URL匹配
     * @param urlPattern url正则表达式
     * @param url 请求url
     * @param projectCode 工程编码
     * @return 是否匹配
     */
    public static boolean isMatchUrl(String urlPattern,String url,String projectCode ){
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        return antPathMatcher.match(handleEndUrl(urlPattern), handleUrl(url, projectCode));

    }

}
